/* 
 * 创建日期 2016-11-10
 *
 * 成都澳乐科技有限公司版权所有
 * 电话：028-85253121 
 * 传真：028-85253121
 * 邮编：610041 
 * 地址：成都市武侯区航空路6号丰德国际C3
 */
package com.itrip.log.module.web;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itrip.log.module.db.IDao;
import com.itrip.log.module.db.KVDB;
import com.itrip.log.module.db.domain.KeyWordAlarm;
import com.itrip.log.module.db.server.AlarmManager;
import com.itrip.log.util.MailQueue;

/**
 * Function:前端错误搜集
 *
 * @date:2017年1月24日/上午9:36:47
 * @Author:jeff.cao@aoliday.com
 * @version:1.0
 */
@Controller
@RequestMapping("/err")
public class ErrorController extends BaseController {

	private static Logger LOG = LoggerFactory.getLogger(ErrorController.class);

	@Autowired
	protected AlarmManager alarmManager;

	@Autowired
	protected MailQueue mQueue;

	@Autowired
	@Qualifier("daoTemplate")
	private IDao daoTemplate;
	
	@Autowired
	private  KVDB kvdb;

	@ResponseBody
	@RequestMapping("/add")
	public String addError(HttpServletRequest req, String host, String path, String error) {
		try {
			kvdb.put(host, "1");
			StringBuffer info = new StringBuffer();
			String header = req.getHeader("User-Agent");
			error = error.replaceAll("\n", "<br>");
			
			info.append("browser:").append(header).append("<br>");
			info.append("path:").append(path).append("<br>");
			info.append("error:").append(error).append("<br>");
			testLogMatchKeyword(host, info);
		} catch (Exception e) {
			LOG.info("ui log error:" + error, e);
		}
		return "ok";
	}

	private void testLogMatchKeyword(String host, StringBuffer all) {
		for (KeyWordAlarm kw : alarmManager.getKwRules()) {
			String filePath = kw.getFilePath();
			if (!filePath.startsWith(host))
				continue;

			if (isMatch(all, kw.getExclude())) {
				LOG.info("match exclude:{},skip:{}", kw.getExclude(), all);
				continue;
			}

			if (isMatch(all, kw.getKeyword())) {
				mQueue.addEmailTask(kw.getEmailGroup(), host, all, kw.getKeyword());
				break;
			}
		}
	}

	private boolean isMatch(StringBuffer all, String keyword) {
		if (StringUtils.isEmpty(keyword))
			return false;

		for (String string : keyword.split(",")) {
			if (all.indexOf(string) > -1) {
				return true;
			}
		}
		return false;
	}
}
